package com.example.textview.datastorage;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.textview.R;
public class SharedPreferenceActivity extends AppCompatActivity implements View.OnClickListener {

    EditText et_name;
    Button btn_save,btn_show;
    TextView tv_show;
    SharedPreferences msharedPreferences;
    SharedPreferences.Editor meditor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_preference);

        et_name=findViewById(R.id.et_name);
        tv_show=findViewById(R.id.tv_show);
        btn_save=findViewById(R.id.btn_save);
        btn_show=findViewById(R.id.btn_show);
        btn_save.setOnClickListener(this);
        btn_show.setOnClickListener(this);

        //MODE_PRIVATE 本应用才可以读写
        msharedPreferences=getSharedPreferences("filename",MODE_PRIVATE);
        meditor= msharedPreferences.edit();
    }

    @Override
    public void onClick(View view) {

        switch (view.getId())
        {
            case R.id.btn_save:
                meditor.putString("name",et_name.getText().toString());
                //meditor.commit();//同步
                meditor.apply();//异步  都可以
                break;

            case R.id.btn_show:
                tv_show.setText(msharedPreferences.getString("name","默认值").toString());
                break;

        }
    }
}